package com.hy.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hy.domain.Blog;
import com.hy.domain.User;
import com.hy.domain.dto.BlogDTO;
import com.hy.domain.dto.R;
import com.hy.domain.dto.UserDTO;
import com.hy.service.BlogService;
import com.hy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;

    @Autowired
    private UserService userService;

    /**
     * 获取Blog列表
     * @param page 页码
     * @param size 页大小
     * @param keyword 搜索关键词
     * @return
     */
    @GetMapping
    public R list(int page, int size, String keyword) {
        final Page result = blogService.listPagesByQuery(page, size, keyword);
        List collect = (List) result.getRecords()
                .stream()
                .map(blog -> {
                    final BlogDTO blogDTO = BeanUtil.copyProperties(blog, BlogDTO.class);
                    final User user = userService.getById(blogDTO.getUserId());
                    final UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
                    blogDTO.setUser(userDTO);
                    return blogDTO;
                })
                .collect(Collectors.toList());
        result.setRecords(collect);
        return R.ok(result);
    }

    @GetMapping("/user/{id}")
    public R listByUser(@PathVariable Long id, int page, int size) {
        final IPage result = blogService.listPagesByUser(id, page, size);
        return R.ok(result);
    }

    /**
     * 根据id获取Blog
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Blog> getBlog(@PathVariable long id) {
        final BlogDTO result = blogService.getBlogById(id);
        return R.ok(result);
    }

    /**
     * 添加Blog
     * @param blog
     * @return
     */
    @PostMapping()
    public R add(@RequestBody Blog blog) {
        System.out.println("blog = " + blog);
        blogService.saveBlog(blog);
        return R.ok().message("添加成功");
    }

    /**
     * 根据id删除Blog
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public R<Blog> delete(@PathVariable long id) {
        final boolean success = blogService.removeById(id);
        return R.by(success);
    }

    /**
     * 修改Blog
     * @param blog
     * @return
     */
    @PutMapping()
    public R<Blog> update(@RequestBody Blog blog) {
        return blogService.updateBlog(blog);
    }

}
